# coding: utf-8
import time
import json
from datetime import timedelta, datetime
from random import randrange

from functools import wraps
from flask import request
from flask import session
from flask import redirect, url_for
from flask import render_template
from flask import Blueprint

from leancloud import Object, Query, User
from tools import logging
from dbModels import AgmSucGetJf, AgmFwCode, Cache_dict

agmsell_view = Blueprint('agmsell', __name__, template_folder='../templates/agmsell')

timestamp = int(time.time())
SELLITEMS = 'AgmsellItem'
QRRECORD = 'AgmQrRecord'
SUCSELL = 'AgmsellSucSelled'
USER = 'AgmsellUser'


def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if 'agmsell' in session:
            return func(*args, **kwargs)
        else:
            return redirect(url_for('agmsell.login'))
    return wrapper


@agmsell_view.route('/')
@login_required
def index():
    qritems = Query(Object.extend(SELLITEMS)).equal_to(
        'agmsellid', session.get('agmsell')
    ).descending('createdAt').find()
    agmsell = Query(Object.extend(USER)).get(session.get('agmsell'))
    return render_template('main.html', timestamp=timestamp, 
        qritems=qritems, agmsell=agmsell)
        
@agmsell_view.route('/selllist')
@login_required
def selllist():
    sell_list = Query(Object.extend(SUCSELL)).equal_to(
        'agmsellid', session.get('agmsell')
    ).descending('createdAt').find()
    agmsell = Query(Object.extend(USER)).get(session.get('agmsell'))    
    for t in sell_list:
        t.created_at = t.created_at + timedelta(hours=8)
    return render_template('selllist.html', timestamp=timestamp, 
        sell_list=sell_list, agmsell=agmsell)        

    
@agmsell_view.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        roles = {'admin', 'agmsell'}
        name = request.form.get('name')
        password = request.form.get('password')
        user = User()
        try:
            user.login(name, password)
        except Exception as e:
            if e.code == 211:
                return 'nouser'
            elif e.code == 210:
                return 'passworderror'
            return '%s' % e.code
        if user.get('role') in roles:
            try:
                agmselluser = Query(Object.extend(USER)).equal_to('user', user).first()
            except:
                return 'usernobind'
            session['agmsell'] = agmselluser.id
            return 'Done!'
        return 'user:%s' % user.dump()
    return render_template('login.html')
    
@agmsell_view.route('/manage', methods=['POST'])
@logging.log
def manage():
    actions = {'additem': additem, 'createqr': createqr,
        'checkqrstat': checkqrstat, 'wechatbind': wechatbind,
        'shortcutbind': shortcutbind, 'wechatunbind': wechatunbind,
        'wechatmessage': wechatmessage}
    action = request.args.get('action')
    if action in actions:
        return actions[action]()
    return 'managePost!'
    
def additem():
    if not session.get('agmsell'):
        return 'nosession'
    title = request.form.get('title')
    cost = request.form.get('cost')
    if title and cost:
        try:
            cost = int(cost)
        except ValueError:
            return 'errorcost'
        agmsellitem = Object.extend(SELLITEMS)()
        agmsellitem.set('title', title).set('cost', cost)
        agmsellitem.set('agmsellid', session.get('agmsell')).save()
        return json.dumps(dict(lcid=agmsellitem.id, cost=cost, title=title))
    return 'error:%s|%s' % (title, cost)
    
def createqr():
    if not session.get('agmsell'):
        return 'nosession'    
    pid = request.form.get('pid')
    try:
        qritem = Query(Object.extend(SELLITEMS)).get(pid)
        if qritem.get('agmsellid') != session.get('agmsell'):
            return 'permissionDeny'
    except:
        return 'qritemerror'
    agmsellid=session.get('agmsell')
    randint = randrange(1, 100000)
    qrrecord = createqrrecord(randint, agmsellid, qritem)
    from tools.wechatAPI import getqrcode
    ret = getqrcode(randint)

    if 'qrurl' in ret:
        return json.dumps(dict(qrurl=ret['qrurl'], qrid=qrrecord.id))
        
def createqrrecord(randint, agmsellid, qritem):
    qrrecord = Object.extend(QRRECORD)(agmsellid=agmsellid)
    qrrecord.set('randint', randint).set('qritem', qritem)
    qrrecord.set('addtime', int(time.time())).save()
    return qrrecord
        
def checkqrstat():
    if not session.get('agmsell'):
        return 'nosession'
    qrid = request.form.get('qrid')
    expire = 60
    try:
        qrrecord = Query(Object.extend(QRRECORD)).get(qrid)
        if qrrecord.get('agmsellid') != session.get('agmsell'):
            return 'permissionDeny'
        if qrrecord.get('addtime') < time.time() - expire:
            return 'expired'
    except:
        return 'qrrecorderror'
    if qrrecord.get('stat'):
        return 'done'
    return 'wait'

def validqrcode(qrcode, openid):
    if qrcode in ['99999', '99998', '99997', '99996']:
        return tyhd(openid, qrcode)
    try:
        qrcode = int(qrcode)
    except:
        return 'intParseFaild %s' % qrcode
    query = Query(Object.extend(QRRECORD))
    query.equal_to('randint', int(qrcode))
    query.not_equal_to('stat', 1)
    expire = 60
    query.greater_than('addtime', time.time() - expire)
    ret = query.find()
    if ret:
        ret = ret[0]
        if ret.get('jf') and ret.get('code'):
            wechatuser = Query(Object.extend('WechatUser')).equal_to('openid', openid).find()
            if not wechatuser:
                return 'UserDeleted'
            incr_jf = ret.get('jf')
            code = ret.get('code')
            fwcode = Query(AgmFwCode).equal_to('code', code).first()
            if fwcode.get('status') != 0:
                return u'该防伪码已经被获取过积分'
            wechatuser = wechatuser[0]
            wechatuser.increment('jf', incr_jf).save()
            AgmSucGetJf(openid=openid, jf=incr_jf, code=code).save()
            fwcode.set('status', 1).save()
            ret.set('stat', 1).save()
            return u'扫码成功获%s积分\n当前积分为:%s' % (incr_jf, wechatuser.get('jf'))            
        qritem = ret.get('qritem')
        qritem.fetch()
        agmsellid = qritem.get('agmsellid')
        agmsell = Query(Object.extend(USER)).get(agmsellid)
        cost = qritem.get('cost')
        wechatuser = Query(Object.extend('WechatUser')).equal_to('openid', openid).find()
        if not wechatuser:
            return 'UserDeleted'
        wechatuser = wechatuser[0]
        jf = wechatuser.get('jf')
        if jf - cost < 0:
            return u'本次消费需要%s积分\n当前积分为:%s\n不够消费额度' % (cost, jf)
        wechatuser.increment('jf', -cost).save()
        agmsell.increment('selljf', cost).save()
        sucsell = Object.extend(SUCSELL)()
        sucsell.set('agmsellid', qritem.get('agmsellid'))
        sucsell.set('memberopenid', openid)
        sucsell.set('title', qritem.get('title'))
        sucsell.set('cost', cost)
        sucsell.save()
        ret.set('stat', 1).save()
        if agmsell.get('messageswitch') and agmsell.get('openid'):
            from tools.wechatAPI import sendmessage
            sendmessage(agmsell.get('openid'), 
                u'二维码验证通过\n交易标题:%s\n交易积分:%s' % (qritem.get('title'), qritem.get('cost')))
        return u'操作成功:%s\n消费积分:%s\n当前积分为:%s' % (
            qritem.get('title'), qritem.get('cost'), wechatuser.get('jf'))
    return u'该二维码无效或已经使用过'
    
def wechatbind():
    wechatuserid = session.get('wechatuserid')
    agmsellid = session.get('agmsell')
    if wechatuserid and agmsellid:
        try:
            agmsell = Query(Object.extend(USER)).get(agmsellid)
            wechatuser = Query(Object.extend('WechatUser')).get(wechatuserid)
        except:
            return 'WechatidOrAgmsellidError'
        agmsell.set('openid', wechatuser.get('openid'))
        agmsell.save()
        return 'done'
    return 'sessionfail'
    
def shortcutbind():
    agmsellid = session.get('agmsell')
    if not agmsellid:
        return 'nosession'
    key = request.form.get('shortcut')
    if not key.startswith('@'):
        return 'notstartswith@'
    qritemid = request.form.get('lc_id')
    items = Query(Object.extend(SELLITEMS)).equal_to('shortcut', key).find()
    if items:
        return 'done' if items[0].id == qritemid else 'repeat'
    qritem = Query(Object.extend(SELLITEMS)).get(qritemid)
    if qritem.get('agmsellid') != agmsellid:
        return 'PermissionDeny'
    qritem.set('shortcut', key).save()
    return 'done'

def wechatunbind():
    agmsellid = session.get('agmsell')
    if not agmsellid:
        return 'nosession'
    Query(Object.extend(USER)).get(agmsellid).unset('openid').save()
    return 'done'
    
def wechatmessage():
    agmsellid = session.get('agmsell')
    if not agmsellid:
        return 'nosession'
    try:
        agmsell = Query(Object.extend(USER)).get(agmsellid)
    except:
        return 'noagmsellfound'
    switch = request.form.get('messageswitch')
    if switch == 'on':
        agmsell.set('messageswitch', True).save()
    else:
        agmsell.unset('messageswitch').save()    
    return 'done'
    
def sendqrtowechat(keyword, openid):
    try:
        agmsell = Query(Object.extend(USER)).equal_to('openid', openid).first()
    except:
        # return 'nowchatbind'
        return u'当前微信号无绑定任何销售帐号'
    if not agmsell.get('messageswitch'):
        # return 'wechatstopdisplay'
        return u'该绑定销售号停用了微信提示信息'
    query = Query(Object.extend(SELLITEMS))
    query.equal_to('agmsellid', agmsell.id).equal_to('shortcut', keyword)
    qritem = query.find()
    if not qritem:
        # return 'nothiskeyword'
        return u'无此快捷关键字'
    qritem =qritem[0]
    randint = randrange(1, 99990)
    createqrrecord(randint, agmsell.id, qritem)
    from tools.wechatAPI import sendqrcode
    sendqrcode(openid, randint)
    return u'成功生成以下二维码图片\n标题:%s\n需积分:%s' % (
        qritem.get('title'), qritem.get('cost'))
    
    
def tyhd(openid, qrcode):
    #2016-5-26日添加，体验券功能
    if datetime.utcnow() + timedelta(hours=8) < datetime(2016, 6, 3):
        codedict = {
            '99999': (u'恭喜获得音速风暴5元体验抵用券', '00ovWPMgUJQEgas8wvfqsVRvxnUbk331yszSUMmNocE'),
            '99998': (u'恭喜挑战成功，获得50元音速风暴产品抵用券', '00ovWPMgUJQEgas8wvfqsSSU7Rn9TaCroZXhKuo7DKI'),
        }
        codedict = Query(Cache_dict).get('5746b7e471cfe4006bc0c1e3').get('content')
        if qrcode in codedict:
            tytime = time.time()
            AgmTyhd = Object.extend('AgmTyhd')
            AgmTyhd(openid=openid, qrcode=qrcode, tytime=tytime).save()
            from tools.wechatAPI import sendmessage
            sendmessage(openid, codedict[qrcode][1], 'image')
            return codedict[qrcode][0]    
        
    if datetime.utcnow().hour + 8 < 8 or datetime.utcnow().hour + 8 >= 22:
        return u'请在早上8:00-晚上10:00期间扫描本体验二维码'
    codedict = {
        '99999': (u'北京丰台区丰葆路永旺百货', 10), 
        '99998': (u'北京丰台区丰葆路永旺百货', 15),
        '99997': (u'北京西城区右安门内王府井百货', 10),
        '99996': (u'北京西城区右安门内王府井百货', 15),
    }
    codedict = Query(Cache_dict).get('574560f55bbb50005786913f').get('content')
    if qrcode not in codedict:
        return u'抱歉，该二维码已经失效！感谢您对音速风暴活动的支持。'
    meidaid = {
        10: '00ovWPMgUJQEgas8wvfqsVRvxnUbk331yszSUMmNocE',
        15: '00ovWPMgUJQEgas8wvfqsSSU7Rn9TaCroZXhKuo7DKI'
    }
    AgmTyhd = Object.extend('AgmTyhd')
    query = Query(AgmTyhd).equal_to('openid', openid).equal_to('qrcode', qrcode)
    todaytimestamp = time.mktime(datetime.now().date().timetuple())
    query.greater_than('tytime', todaytimestamp)
    agmtyhd = query.find()
    if agmtyhd:
        tytime = agmtyhd[0].get('tytime')
        timestr = datetime.fromtimestamp(tytime).strftime('%Y-%m-%d %H:%M')
        return u'抱歉, 你今日已经扫描过本二维码, 扫描时间:%s' % timestr
    tytime = time.time()
    timestr = datetime.fromtimestamp(tytime).strftime('%Y-%m-%d %H:%M')
    AgmTyhd(openid=openid, qrcode=qrcode, tytime=tytime).save()
    from tools.wechatAPI import sendmessage
    sendmessage(openid, meidaid[codedict[qrcode][1]], 'image')
    content =  u'恭喜您获得音速风暴“%s元”现金抵用券，请在“%s”使用此优惠\n获取时间:%s' % (codedict[qrcode][1], codedict[qrcode][0], timestr)
    return content